/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: lai_hq@qq.com
 * @Date: 2022-07-30 13:40:31
 * @LastEditors: lai_hq@qq.com
 * @LastEditTime: 2022-08-05 14:32:23
 */
import { createStore } from 'vuex'

import createPersistedState from 'vuex-persistedstate'

import { useStorage } from '@/utils/index'

const modulesFiles = import.meta.globEager('./modules/*.ts')
const pathList = []

// eslint-disable-next-line no-restricted-syntax
for (const path in modulesFiles) {
    if (path) {
        pathList.push(path)
    }
}

// eslint-disable-next-line no-shadow
const modules = pathList.reduce((modules, modulePath: string) => {
    const moduleName = modulePath.replace(/^\.\/modules\/(.*)\.\w+$/, '$1')
    const value = modulesFiles[modulePath] as { default: any }
    /* eslint no-param-reassign: "error" */
    modules[moduleName] = value.default
    return modules
}, {} as { [x: string]: any })

const defaultState = {
    count: 0
}

export default createStore({
    modules,
    plugins: [
        createPersistedState({
            ...useStorage(),
            key: 'ACCESS_DATA',
            paths: ['user'] // 指定模
        })
    ],
    state() {
        return defaultState
    },
    mutations: {
        increment(state: typeof defaultState) {
            // eslint-disable-next-line no-param-reassign
            state.count += 1
        }
    },
    actions: {
        increment(context) {
            context.commit('increment')
        }
    },
    getters: {
        double(state: typeof defaultState) {
            return 2 * state.count
        }
    }
})
